package com.graduation.clientback.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.graduation.clientback.common.R;
import com.graduation.clientback.domain.Project;
import com.graduation.clientback.domain.Work;
import com.graduation.clientback.service.ProjectService;
import com.graduation.clientback.service.WorkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/project")
public class ProjectController {

    @Autowired
    private ProjectService projectService;

    @Autowired
    private WorkService workService;

    /**
     * 查看项目演示详情
     * @param workId
     * @return
     */
    @GetMapping("/detail")
    public R<Project> detail(Long workId) {
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Project::getWorkId, workId);
        Project project = projectService.getOne(queryWrapper);
        return R.success(project);
    }

    /**
     * 提交项目演示
     * @param project
     * @return
     */
    @Transactional
    @PutMapping("/update")
    public R<String> handleProject(@RequestBody Project project) {
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Project::getWorkId, project.getWorkId());
        Project existProject = projectService.getOne(queryWrapper);
        // 不存在
        if(existProject == null) {
            project.setCreateTime(LocalDateTime.now());
            project.setUpdateTime(LocalDateTime.now());
            projectService.save(project);
            Work work = workService.getById(project.getWorkId());
            work.setProcess(work.getProcess() + 33);
            workService.updateById(work);
        } else {
            // 存在
            project.setUpdateTime(LocalDateTime.now());
            projectService.updateById(project);
        }
        return R.success("提交成功");
    }
}
